# -*- coding: utf-8 -*-
"""
智慧职教MOOC视频下载器 - 浏览器管理模块
负责浏览器的初始化、连接和清理
"""

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import WebDriverException, TimeoutException
import time
import contextlib
from config import config
from logger import logger
from exceptions import BrowserConnectionError, PageLoadTimeoutError


class BrowserManager:
    """浏览器管理器，负责浏览器的初始化、连接和清理"""
    
    def __init__(self):
        self.driver = None
        self.main_window = None
        self._connection_verified = False
        
    def initialize_browser(self):
        """初始化浏览器连接"""
        logger.info("正在初始化浏览器连接...")
        
        try:
            # 首先清理现有窗口
            self._cleanup_existing_windows()
            
            # 创建主driver
            self.driver = self._create_driver()
            self.driver.get(config.MOOC_INDEX_URL)
            time.sleep(3)
            
            # 验证连接
            if self._verify_connection():
                self.main_window = self.driver.current_window_handle
                self._connection_verified = True
                logger.success("浏览器初始化完成")
                return True
            else:
                raise BrowserConnectionError("浏览器连接验证失败")
                
        except Exception as e:
            logger.error(f"浏览器初始化失败: {e}")
            self._show_connection_help()
            return False
    
    def _create_driver(self):
        """创建WebDriver实例"""
        options = Options()
        options.add_experimental_option("debuggerAddress", config.CHROME_DEBUG_ADDRESS)
        options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})
        
        # 添加更多选项以提高稳定性
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        options.add_argument('--disable-blink-features=AutomationControlled')
        options.add_experimental_option("excludeSwitches", ["enable-automation"])
        options.add_experimental_option('useAutomationExtension', False)
        
        try:
            driver = webdriver.Chrome(options=options)
            # 隐藏自动化标识
            driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
            return driver
        except Exception as e:
            raise BrowserConnectionError(f"无法创建WebDriver实例: {e}")
    
    def _verify_connection(self):
        """验证浏览器连接是否正常"""
        try:
            # 检查基本连接
            title = self.driver.title
            current_url = self.driver.current_url
            
            logger.debug(f"当前页面标题: {title}")
            logger.debug(f"当前页面URL: {current_url}")
            
            # 检查是否在正确的网站
            if "mooc.icve.com.cn" not in current_url:
                logger.warning("当前页面不是智慧职教MOOC网站")
                return False
            
            return True
            
        except Exception as e:
            logger.error(f"连接验证失败: {e}")
            return False
    
    def _cleanup_existing_windows(self):
        """清理现有窗口"""
        try:
            logger.progress("正在清理现有浏览器窗口...")
            
            # 创建临时driver用于清理
            with self._create_temporary_driver() as temp_driver:
                all_handles = temp_driver.window_handles
                logger.debug(f"发现 {len(all_handles)} 个窗口")
                
                if len(all_handles) > 0:
                    self._close_excess_windows(temp_driver, all_handles)
                    
                logger.success("窗口清理完成")
                
        except Exception as e:
            logger.warning(f"窗口清理失败，继续初始化: {e}")
    
    @contextlib.contextmanager
    def _create_temporary_driver(self):
        """创建临时driver的上下文管理器"""
        temp_driver = None
        try:
            temp_driver = self._create_driver()
            yield temp_driver
        finally:
            if temp_driver:
                try:
                    temp_driver.quit()
                except Exception:
                    pass
    
    def _close_excess_windows(self, driver, handles):
        """关闭多余的窗口"""
        for i, handle in enumerate(handles):
            try:
                driver.switch_to.window(handle)
                current_url = driver.current_url
                
                if i == 0:
                    # 主窗口导航到主页
                    driver.get(config.MOOC_INDEX_URL)
                    logger.debug("主窗口已导航到主页面")
                else:
                    # 关闭其他窗口
                    driver.close()
                    logger.debug(f"已关闭窗口 {i+1}: {current_url[:50]}...")
                    
            except Exception as e:
                logger.warning(f"处理窗口 {i+1} 时出错: {e}")
        
        # 切换回主窗口
        if handles:
            try:
                driver.switch_to.window(handles[0])
            except Exception as e:
                logger.warning(f"切换主窗口时出错: {e}")
    
    def close_all_pages(self):
        """关闭所有浏览器页面，只保留一个空白页面"""
        if not self.check_connection():
            logger.warning("浏览器连接已断开，无法清理页面")
            return
            
        try:
            logger.progress("正在关闭所有页面...")
            
            all_handles = self.driver.window_handles
            logger.debug(f"发现 {len(all_handles)} 个窗口")
            
            if len(all_handles) == 0:
                logger.info("没有找到任何窗口")
                return
            
            closed_count = 0
            for i, handle in enumerate(all_handles):
                try:
                    self.driver.switch_to.window(handle)
                    current_url = self.driver.current_url
                    
                    if i == 0:
                        # 主窗口导航到空白页
                        self.driver.get("about:blank")
                        logger.debug(f"主窗口已导航到空白页 (原页面: {current_url[:50]}...)")
                    else:
                        # 关闭其他窗口
                        self.driver.close()
                        closed_count += 1
                        logger.debug(f"已关闭窗口 {i+1} (页面: {current_url[:50]}...)")
                        time.sleep(0.5)
                        
                except Exception as e:
                    logger.warning(f"处理窗口 {i+1} 时出错: {e}")
            
            # 切换回主窗口
            if all_handles:
                try:
                    self.driver.switch_to.window(all_handles[0])
                    logger.debug("已切换回主窗口")
                except Exception as e:
                    logger.warning(f"切换主窗口时出错: {e}")
            
            logger.success(f"页面清理完成！关闭了 {closed_count} 个窗口，保留 1 个空白页")
            
        except Exception as e:
            logger.error(f"关闭页面时出错: {e}")
    
    def get_driver(self):
        """获取driver实例"""
        if not self._connection_verified:
            logger.warning("浏览器连接未验证，可能出现问题")
        return self.driver
    
    def get_main_window(self):
        """获取主窗口句柄"""
        return self.main_window
    
    def check_connection(self):
        """检查driver连接状态"""
        try:
            if self.driver:
                # 简单检查连接
                _ = self.driver.title
                return True
        except (WebDriverException, AttributeError) as e:
            logger.warning(f"浏览器连接已断开: {e}")
            self._connection_verified = False
            return False
        return False
    
    def reconnect(self):
        """重新连接浏览器"""
        logger.progress("尝试重新连接浏览器...")
        
        # 清理当前连接
        self._cleanup_current_connection()
        
        # 重新初始化
        return self.initialize_browser()
    
    def _cleanup_current_connection(self):
        """清理当前连接"""
        if self.driver:
            try:
                self.driver.quit()
            except Exception:
                pass
            finally:
                self.driver = None
                self.main_window = None
                self._connection_verified = False
    
    def _show_connection_help(self):
        """显示连接帮助信息"""
        logger.error("无法建立浏览器连接")
        logger.info("请确保：")
        logger.info("1. Chrome浏览器已启动")
        logger.info("2. 浏览器已开启远程调试模式")
        logger.info(f"3. 启动命令：chrome.exe --remote-debugging-port={config.CHROME_DEBUG_PORT}")
        logger.info("4. 在浏览器中已登录智慧职教MOOC账号")
    
    def __enter__(self):
        """上下文管理器入口"""
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """上下文管理器出口"""
        self._cleanup_current_connection()


def manual_close_pages():
    """手动关闭所有浏览器页面的独立工具"""
    try:
        logger.info("=" * 60)
        logger.info("🧹 智慧职教MOOC - 手动关闭页面工具")
        logger.info("=" * 60)
        
        with BrowserManager() as browser_manager:
            # 不需要完整初始化，只需要创建driver
            browser_manager.driver = browser_manager._create_driver()
            logger.success("已连接到浏览器")
            
            browser_manager.close_all_pages()
            
    except Exception as e:
        logger.error(f"操作失败: {e}")
        logger.info("请确保：")
        logger.info("1. Chrome浏览器已启动")
        logger.info("2. 浏览器已开启远程调试模式")
        logger.info(f"3. 启动命令：chrome.exe --remote-debugging-port={config.CHROME_DEBUG_PORT}") 